<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';

// Props for customization
const props = defineProps({
  progress: {
    type: Number,
    default: 0,
    validator: (value) => value >= 0 && value <= 100
  },
  message: {
    type: String,
    default: 'Loading...'
  },
  showProgress: {
    type: Boolean,
    default: false
  },
  theme: {
    type: String,
    default: 'purple',
    validator: (value) => ['purple', 'blue', 'green', 'orange'].includes(value)
  }
});

// Reactive state
const particles = ref([]);
const orbitParticles = ref([]);
const loadingStage = ref(0);
const animationFrame = ref(null);
const startTime = ref(Date.now());

// Computed properties
const progressPercentage = computed(() => Math.min(Math.max(props.progress, 0), 100));
const currentMessage = computed(() => {
  if (props.showProgress) {
    return `${props.message} ${progressPercentage.value}%`;
  }
  return props.message;
});

// Theme colors
const themes = {
  purple: {
    primary: '#9333ea',
    secondary: '#c084fc',
    accent: '#e879f9',
    gradient: 'linear-gradient(135deg, #0f172a, #581c87, #1e1b4b)'
  },
  blue: {
    primary: '#3b82f6',
    secondary: '#60a5fa',
    accent: '#93c5fd',
    gradient: 'linear-gradient(135deg, #0c1426, #1e3a8a, #1e40af)'
  },
  green: {
    primary: '#10b981',
    secondary: '#34d399',
    accent: '#6ee7b7',
    gradient: 'linear-gradient(135deg, #0c1415, #065f46, #047857)'
  },
  orange: {
    primary: '#f59e0b',
    secondary: '#fbbf24',
    accent: '#fcd34d',
    gradient: 'linear-gradient(135deg, #1c1917, #92400e, #d97706)'
  }
};

const currentTheme = computed(() => themes[props.theme]);

// Generate particles
const generateParticles = () => {
  particles.value = Array.from({ length: 30 }, (_, index) => ({
    id: index,
    left: `${Math.random() * 100}%`,
    top: `${Math.random() * 100}%`,
    size: Math.random() * 6 + 2,
    duration: 3 + Math.random() * 4,
    delay: Math.random() * 3,
    opacity: Math.random() * 0.5 + 0.2,
    direction: Math.random() > 0.5 ? 1 : -1
  }));
};

// Generate orbit particles
const generateOrbitParticles = () => {
  orbitParticles.value = Array.from({ length: 8 }, (_, index) => ({
    id: index,
    angle: (index * 45) * (Math.PI / 180),
    radius: 60 + (index % 2) * 20,
    speed: 0.02 + Math.random() * 0.01,
    size: 4 + Math.random() * 4
  }));
};

// Update orbit particles animation
const updateOrbitParticles = () => {
  orbitParticles.value.forEach(particle => {
    particle.angle += particle.speed;
  });
  animationFrame.value = requestAnimationFrame(updateOrbitParticles);
};

// Loading stage progression
const updateLoadingStage = () => {
  const elapsed = Date.now() - startTime.value;
  loadingStage.value = Math.floor((elapsed / 1000) % 4);
};

// Lifecycle hooks
onMounted(() => {
  generateParticles();
  generateOrbitParticles();
  updateOrbitParticles();

  // Update loading stage every second
  const stageInterval = setInterval(updateLoadingStage, 1000);

  onBeforeUnmount(() => {
    if (animationFrame.value) {
      cancelAnimationFrame(animationFrame.value);
    }
    clearInterval(stageInterval);
  });
});

onBeforeUnmount(() => {
  if (animationFrame.value) {
    cancelAnimationFrame(animationFrame.value);
  }
});
</script>

<template>
  <div
      class="loader-container"
      role="alertdialog"
      aria-busy="true"
      aria-live="polite"
      :aria-label="currentMessage"
      :style="{ background: currentTheme.gradient }"
  >
    <!-- Enhanced backdrop with animated gradient -->
    <div class="backdrop-enhanced">
      <div class="gradient-overlay"></div>
      <div class="noise-overlay"></div>
    </div>

    <!-- Main loader container with 3D effect -->
    <div class="loader-wrapper">
      <!-- Central loading hub -->
      <div class="loading-hub">
        <!-- Rotating outer ring -->
        <div class="outer-ring" :style="{ borderColor: currentTheme.primary }">
          <div class="ring-segment" v-for="i in 12" :key="`outer-${i}`"
               :style="{
                 transform: `rotate(${i * 30}deg) translateY(-40px)`,
                 backgroundColor: currentTheme.secondary,
                 animationDelay: `${i * 0.1}s`
               }"></div>
        </div>

        <!-- Middle ring -->
        <div class="middle-ring" :style="{ borderColor: currentTheme.secondary }">
          <div class="ring-segment" v-for="i in 8" :key="`middle-${i}`"
               :style="{
                 transform: `rotate(${i * 45}deg) translateY(-25px)`,
                 backgroundColor: currentTheme.accent,
                 animationDelay: `${i * 0.15}s`
               }"></div>
        </div>

        <!-- Inner core with pulsing effect -->
        <div class="inner-core" :style="{ backgroundColor: currentTheme.primary }">
          <div class="core-pulse" :style="{ backgroundColor: currentTheme.accent }"></div>
        </div>

        <!-- Orbit particles -->
        <div class="orbit-container">
          <div
              v-for="particle in orbitParticles"
              :key="`orbit-${particle.id}`"
              class="orbit-particle"
              :style="{
              left: `${50 + Math.cos(particle.angle) * particle.radius}px`,
              top: `${50 + Math.sin(particle.angle) * particle.radius}px`,
              width: `${particle.size}px`,
              height: `${particle.size}px`,
              backgroundColor: currentTheme.accent,
              boxShadow: `0 0 ${particle.size * 2}px ${currentTheme.accent}`
            }"
          ></div>
        </div>
      </div>

      <!-- Enhanced geometric shapes with 3D transforms -->
      <div class="shapes-constellation">
        <div class="shape-group" v-for="(group, groupIndex) in 2" :key="`group-${groupIndex}`">
          <div class="enhanced-shape circle-enhanced"
               :class="{ active: loadingStage === 0 }"
               :style="{
                 borderColor: currentTheme.primary,
                 boxShadow: `0 0 20px ${currentTheme.primary}40`
               }">
            <div class="shape-inner"></div>
          </div>

          <div class="enhanced-shape triangle-enhanced"
               :class="{ active: loadingStage === 1 }"
               :style="{
                 backgroundColor: currentTheme.secondary,
                 boxShadow: `0 0 20px ${currentTheme.secondary}40`
               }"></div>

          <div class="enhanced-shape square-enhanced"
               :class="{ active: loadingStage === 2 }"
               :style="{
                 borderColor: currentTheme.accent,
                 boxShadow: `0 0 20px ${currentTheme.accent}40`
               }">
            <div class="shape-inner"></div>
          </div>

          <div class="enhanced-shape diamond-enhanced"
               :class="{ active: loadingStage === 3 }"
               :style="{
                 backgroundColor: currentTheme.primary,
                 boxShadow: `0 0 20px ${currentTheme.primary}40`
               }"></div>
        </div>
      </div>
    </div>

    <!-- Progress bar (if enabled) -->
    <div v-if="showProgress" class="progress-container">
      <div class="progress-bar">
        <div class="progress-fill"
             :style="{
               width: `${progressPercentage}%`,
               background: `linear-gradient(90deg, ${currentTheme.primary}, ${currentTheme.secondary})`
             }"></div>
      </div>
      <div class="progress-text">{{ progressPercentage }}%</div>
    </div>

    <!-- Enhanced loading text with typewriter effect -->
    <div class="loading-text-container">
      <div class="loading-text" :style="{ color: currentTheme.accent }">
        {{ currentMessage }}
      </div>
      <div class="loading-dots">
        <span class="dot" :style="{ backgroundColor: currentTheme.primary }"></span>
        <span class="dot" :style="{ backgroundColor: currentTheme.secondary }"></span>
        <span class="dot" :style="{ backgroundColor: currentTheme.accent }"></span>
      </div>
    </div>

    <!-- Enhanced particles system -->
    <div class="particles-container">
      <!-- Floating particles -->
      <div
          v-for="particle in particles"
          :key="`particle-${particle.id}`"
          class="enhanced-particle"
          :style="{
          left: particle.left,
          top: particle.top,
          width: `${particle.size}px`,
          height: `${particle.size}px`,
          opacity: particle.opacity,
          animationDuration: `${particle.duration}s`,
          animationDelay: `${particle.delay}s`,
          backgroundColor: currentTheme.accent
        }"
      ></div>

      <!-- Energy streams -->
      <div class="energy-streams">
        <div v-for="i in 6" :key="`stream-${i}`"
             class="energy-stream"
             :style="{
               transform: `rotate(${i * 60}deg)`,
               background: `linear-gradient(90deg, transparent, ${currentTheme.primary}40, transparent)`
             }"></div>
      </div>
    </div>

    <!-- Enhanced pulse rings with multiple layers -->
    <div class="pulse-system">
      <div v-for="i in 4" :key="`pulse-${i}`"
           class="enhanced-pulse-ring"
           :style="{
             width: `${(i + 1) * 4}rem`,
             height: `${(i + 1) * 4}rem`,
             borderColor: currentTheme.primary,
             animationDelay: `${i * 0.5}s`
           }"></div>
    </div>

    <!-- Loading tips (optional) -->
    <div class="loading-tips">
      <div class="tip-text">
        {{ loadingStage === 0 ? 'Initializing...' :
          loadingStage === 1 ? 'Loading resources...' :
              loadingStage === 2 ? 'Processing data...' : 'Almost ready...' }}
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
// Enhanced variables
$shape-size: 2rem;
$animation-duration: 0.8s;
$hub-size: 120px;

// Container with enhanced styling
.loader-container {
  position: fixed;
  inset: 0;
  z-index: 9999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}

// Enhanced backdrop
.backdrop-enhanced {
  position: absolute;
  inset: 0;
  backdrop-filter: blur(8px);
}

.gradient-overlay {
  position: absolute;
  inset: 0;
  background: radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
  animation: gradient-shift 8s ease-in-out infinite;
}

.noise-overlay {
  position: absolute;
  inset: 0;
  opacity: 0.03;
  background-image:
      radial-gradient(circle at 25% 25%, white 2px, transparent 2px),
      radial-gradient(circle at 75% 75%, white 1px, transparent 1px);
  background-size: 50px 50px, 30px 30px;
  animation: noise-drift 20s linear infinite;
}

// Main loader wrapper
.loader-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4rem;
  perspective: 1000px;
}

// Loading hub (central element)
.loading-hub {
  position: relative;
  width: $hub-size;
  height: $hub-size;
  transform-style: preserve-3d;
}

.outer-ring, .middle-ring {
  position: absolute;
  top: 50%;
  left: 50%;
  border: 2px solid;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}

.outer-ring {
  width: 100px;
  height: 100px;
  animation: rotate-clockwise 4s linear infinite;
}

.middle-ring {
  width: 70px;
  height: 70px;
  animation: rotate-counter-clockwise 3s linear infinite;
}

.ring-segment {
  position: absolute;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  animation: segment-pulse 2s ease-in-out infinite;
}

.inner-core {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  animation: core-pulse 2s ease-in-out infinite;
}

.core-pulse {
  position: absolute;
  inset: 0;
  border-radius: 50%;
  animation: pulse-expand 1.5s ease-out infinite;
}

.orbit-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.orbit-particle {
  position: absolute;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  animation: particle-glow 2s ease-in-out infinite;
}

// Enhanced shapes constellation
.shapes-constellation {
  display: flex;
  gap: 3rem;
  transform-style: preserve-3d;
}

.shape-group {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  align-items: center;
}

.enhanced-shape {
  width: $shape-size;
  height: $shape-size;
  position: relative;
  transition: all 0.3s ease;
  transform-style: preserve-3d;
  animation: shape-float 3s ease-in-out infinite;
}

.enhanced-shape.active {
  transform: scale(1.2) rotateY(180deg);
  filter: brightness(1.5);
}

.circle-enhanced {
  border: 3px solid;
  border-radius: 50%;
  animation-delay: 0s;
}

.triangle-enhanced {
  clip-path: polygon(50% 0%, 100% 100%, 0% 100%);
  animation-delay: 0.2s;
}

.square-enhanced {
  border: 3px solid;
  border-radius: 4px;
  animation-delay: 0.4s;
}

.diamond-enhanced {
  clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
  animation-delay: 0.6s;
}

.shape-inner {
  position: absolute;
  inset: 2px;
  border-radius: inherit;
  background: rgba(255, 255, 255, 0.1);
  animation: inner-glow 2s ease-in-out infinite;
}

// Progress bar
.progress-container {
  position: absolute;
  bottom: 25%;
  width: 300px;
  text-align: center;
}

.progress-bar {
  width: 100%;
  height: 6px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 0.5rem;
}

.progress-fill {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s ease;
  position: relative;
  overflow: hidden;
}

.progress-fill::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  animation: progress-shine 2s ease-in-out infinite;
}

.progress-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.875rem;
  font-weight: 600;
}

// Enhanced loading text
.loading-text-container {
  position: absolute;
  bottom: 15%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.loading-text {
  font-size: 1.25rem;
  font-weight: 600;
  letter-spacing: 0.1em;
  text-align: center;
  animation: text-glow 2s ease-in-out infinite;
}

.loading-dots {
  display: flex;
  gap: 0.5rem;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  animation: dot-bounce 1.4s ease-in-out infinite;
}

.dot:nth-child(1) { animation-delay: 0s; }
.dot:nth-child(2) { animation-delay: 0.2s; }
.dot:nth-child(3) { animation-delay: 0.4s; }

// Enhanced particles
.particles-container {
  position: absolute;
  inset: 0;
  overflow: hidden;
  pointer-events: none;
}

.enhanced-particle {
  position: absolute;
  border-radius: 50%;
  animation: enhanced-float 4s ease-in-out infinite;
}

.energy-streams {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  transform: translate(-50%, -50%);
}

.energy-stream {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 2px;
  transform-origin: 0 50%;
  animation: stream-flow 3s linear infinite;
}

// Enhanced pulse system
.pulse-system {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.enhanced-pulse-ring {
  position: absolute;
  top: 50%;
  left: 50%;
  border: 1px solid;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  animation: enhanced-pulse 3s ease-out infinite;
}

// Loading tips
.loading-tips {
  position: absolute;
  bottom: 8%;
  text-align: center;
}

.tip-text {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.875rem;
  animation: tip-fade 2s ease-in-out infinite;
}

// Animations
@keyframes rotate-clockwise {
  from { transform: translate(-50%, -50%) rotate(0deg); }
  to { transform: translate(-50%, -50%) rotate(360deg); }
}

@keyframes rotate-counter-clockwise {
  from { transform: translate(-50%, -50%) rotate(0deg); }
  to { transform: translate(-50%, -50%) rotate(-360deg); }
}

@keyframes segment-pulse {
  0%, 100% { opacity: 0.3; transform: scale(1); }
  50% { opacity: 1; transform: scale(1.5); }
}

@keyframes core-pulse {
  0%, 100% { transform: translate(-50%, -50%) scale(1); }
  50% { transform: translate(-50%, -50%) scale(1.1); }
}

@keyframes pulse-expand {
  0% { transform: scale(1); opacity: 1; }
  100% { transform: scale(2); opacity: 0; }
}

@keyframes particle-glow {
  0%, 100% { opacity: 0.5; }
  50% { opacity: 1; }
}

@keyframes shape-float {
  0%, 100% { transform: translateY(0) rotateX(0deg); }
  50% { transform: translateY(-10px) rotateX(180deg); }
}

@keyframes inner-glow {
  0%, 100% { opacity: 0.3; }
  50% { opacity: 0.8; }
}

@keyframes progress-shine {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

@keyframes text-glow {
  0%, 100% { text-shadow: 0 0 10px currentColor; }
  50% { text-shadow: 0 0 20px currentColor, 0 0 30px currentColor; }
}

@keyframes dot-bounce {
  0%, 80%, 100% { transform: scale(1); }
  40% { transform: scale(1.3); }
}

@keyframes enhanced-float {
  0%, 100% { transform: translateY(0) translateX(0); opacity: 0.3; }
  25% { transform: translateY(-20px) translateX(10px); opacity: 1; }
  50% { transform: translateY(0) translateX(20px); opacity: 0.7; }
  75% { transform: translateY(20px) translateX(10px); opacity: 1; }
}

@keyframes stream-flow {
  0% { opacity: 0; transform: scaleX(0); }
  50% { opacity: 1; transform: scaleX(1); }
  100% { opacity: 0; transform: scaleX(0); }
}

@keyframes enhanced-pulse {
  0% { transform: translate(-50%, -50%) scale(0.8); opacity: 1; }
  100% { transform: translate(-50%, -50%) scale(2); opacity: 0; }
}

@keyframes gradient-shift {
  0%, 100% { transform: scale(1) rotate(0deg); }
  50% { transform: scale(1.1) rotate(180deg); }
}

@keyframes noise-drift {
  0% { transform: translate(0, 0); }
  100% { transform: translate(-50px, -30px); }
}

@keyframes tip-fade {
  0%, 100% { opacity: 0.6; }
  50% { opacity: 1; }
}

// Responsive design
@media (max-width: 768px) {
  .loader-wrapper {
    flex-direction: column;
    gap: 2rem;
  }

  .shapes-constellation {
    flex-direction: row;
    gap: 1.5rem;
  }

  .progress-container {
    width: 250px;
  }

  .loading-text {
    font-size: 1rem;
  }
}

@media (max-width: 480px) {
  .loading-hub {
    width: 80px;
    height: 80px;
  }

  .outer-ring {
    width: 70px;
    height: 70px;
  }

  .middle-ring {
    width: 50px;
    height: 50px;
  }

  .enhanced-shape {
    width: 1.2rem;
    height: 1.2rem;
  }
}
</style>